use crate::{AppError, AppResult, PageResult, QueryParams, Role, UserStatus};
use chrono::Utc;
use std::collections::HashMap;
use std::sync::Mutex;
use uuid::Uuid;

// 内存中的角色数据存储
lazy_static::lazy_static! {
    static ref ROLES: Mutex<HashMap<String, Role>> = Mutex::new(HashMap::new());
}

// 初始化示例角色数据
fn init_sample_roles() {
    let mut roles = ROLES.lock().unwrap();
    
    // 添加示例角色
    let sample_roles = vec![
        Role {
            id: "role_001".to_string(),
            name: "系统管理员".to_string(),
            code: "admin".to_string(),
            description: Some("系统管理员，拥有所有权限".to_string()),
            status: UserStatus::Active,
            menu_ids: vec!["*".to_string()],
            create_time: Utc::now() - chrono::Duration::days(30),
            update_time: Utc::now() - chrono::Duration::days(5),
        },
        Role {
            id: "role_002".to_string(),
            name: "普通用户".to_string(),
            code: "user".to_string(),
            description: Some("普通用户，基础功能权限".to_string()),
            status: UserStatus::Active,
            menu_ids: vec![
                "dashboard".to_string(),
                "sip:call:list".to_string(),
                "sip:call:make".to_string(),
                "monitor:online:list".to_string(),
            ],
            create_time: Utc::now() - chrono::Duration::days(25),
            update_time: Utc::now() - chrono::Duration::days(3),
        },
        Role {
            id: "role_003".to_string(),
            name: "访客".to_string(),
            code: "guest".to_string(),
            description: Some("访客用户，只读权限".to_string()),
            status: UserStatus::Active,
            menu_ids: vec![
                "dashboard".to_string(),
                "sip:call:list".to_string(),
                "monitor:online:list".to_string(),
            ],
            create_time: Utc::now() - chrono::Duration::days(20),
            update_time: Utc::now() - chrono::Duration::days(1),
        },
    ];
    
    for role in sample_roles {
        roles.insert(role.id.clone(), role);
    }
}

#[tauri::command]
pub async fn get_role_list(params: QueryParams) -> AppResult<PageResult<Role>> {
    // 初始化示例数据
    init_sample_roles();
    
    let roles = ROLES.lock().unwrap();
    let mut role_list: Vec<Role> = roles.values().cloned().collect();
    
    // 应用过滤条件
    if let Some(keyword) = &params.keyword {
        if !keyword.is_empty() {
            role_list.retain(|role| {
                role.name.contains(keyword) ||
                role.code.contains(keyword) ||
                role.description.as_ref().map_or(false, |desc| desc.contains(keyword))
            });
        }
    }
    
    if let Some(status) = &params.status {
        if !status.is_empty() {
            let status_value: i32 = status.parse().unwrap_or(0);
            role_list.retain(|role| {
                let role_status: i32 = role.status.clone().into();
                role_status == status_value
            });
        }
    }
    
    // 分页处理
    let (list, total) = crate::utils::Utils::paginate(
        &role_list,
        params.page,
        params.size,
    );
    
    Ok(PageResult {
        list,
        total,
        page: params.page.unwrap_or(1),
        size: params.size.unwrap_or(10),
    })
}

#[tauri::command]
pub async fn create_role(mut role: Role) -> AppResult<Role> {
    // 验证必填字段
    if role.name.is_empty() {
        return Err(AppError::ValidationError("角色名称不能为空".to_string()));
    }
    
    if role.code.is_empty() {
        return Err(AppError::ValidationError("角色编码不能为空".to_string()));
    }
    
    // 检查角色编码是否已存在
    let roles = ROLES.lock().unwrap();
    if roles.values().any(|r| r.code == role.code) {
        return Err(AppError::ValidationError("角色编码已存在".to_string()));
    }
    
    // 设置角色ID和时间
    role.id = Uuid::new_v4().to_string();
    role.create_time = Utc::now();
    role.update_time = Utc::now();
    
    // 保存角色
    let mut roles = ROLES.lock().unwrap();
    roles.insert(role.id.clone(), role.clone());
    
    Ok(role)
}

#[tauri::command]
pub async fn update_role(role: Role) -> AppResult<Role> {
    let mut roles = ROLES.lock().unwrap();
    
    // 先检查角色编码是否重复（排除自己）
    let has_duplicate = roles.values().any(|r| r.id != role.id && r.code == role.code);
    if has_duplicate {
        return Err(AppError::ValidationError("角色编码已存在".to_string()));
    }
    
    if let Some(existing_role) = roles.get_mut(&role.id) {
        // 更新字段
        existing_role.name = role.name;
        existing_role.code = role.code;
        existing_role.description = role.description;
        existing_role.status = role.status;
        existing_role.menu_ids = role.menu_ids;
        existing_role.update_time = Utc::now();
        
        Ok(existing_role.clone())
    } else {
        Err(AppError::NotFoundError("角色不存在".to_string()))
    }
}

#[tauri::command]
pub async fn delete_role(role_id: String) -> AppResult<()> {
    let mut roles = ROLES.lock().unwrap();
    
    if roles.remove(&role_id).is_some() {
        Ok(())
    } else {
        Err(AppError::NotFoundError("角色不存在".to_string()))
    }
}

#[tauri::command]
pub async fn update_role_status(role_id: String, status: i32) -> AppResult<()> {
    let mut roles = ROLES.lock().unwrap();
    
    if let Some(role) = roles.get_mut(&role_id) {
        role.status = status.into();
        role.update_time = Utc::now();
        Ok(())
    } else {
        Err(AppError::NotFoundError("角色不存在".to_string()))
    }
}

#[tauri::command]
pub async fn get_role_by_id(role_id: String) -> AppResult<Role> {
    let roles = ROLES.lock().unwrap();
    
    roles
        .get(&role_id)
        .cloned()
        .ok_or_else(|| AppError::NotFoundError("角色不存在".to_string()))
}

#[tauri::command]
pub async fn get_all_roles() -> AppResult<Vec<Role>> {
    let roles = ROLES.lock().unwrap();
    Ok(roles.values().cloned().collect())
}

#[tauri::command]
pub async fn export_roles() -> AppResult<Vec<Role>> {
    let roles = ROLES.lock().unwrap();
    Ok(roles.values().cloned().collect())
}
